<?php
require './include/global.php';
require './include/validate.php';
require './include/all_left.php';
include("FCKeditor/fckeditor.php") ;

//Not A Recuiter
if($_SESSION[usertype] != "recruiter" ){
   echo "<meta http-equiv=\"refresh\" content=\"0;URL=errorall.php?errid=rc_1011\">";
   exit;	
}

//jquery
$smarty->assign('jquery',1);
$smarty->assign('tokeninput',1);

$smarty->display('header.tpl');
$smarty->assign("date",date("m-d-Y"));
$smarty->assign("from",$_SESSION['realname']."[".$_SESSION['useremail']."]");



if($_GET['action'] == "view"){
	$eid = $_GET['id']+0;
	if($eid < 1) {
		echo "<meta http-equiv=\"refresh\" content=\"0;URL=errorall.php?errid=rc_1012\">";
		exit;
	}
	$smarty->assign("id",$eid);

	$sql = "SELECT * FROM pa_email WHERE e_id = '".$eid."' AND (e_sentrcid = '".$_SESSION[uid]."' OR e_receivedrcid = '".$_SESSION[uid]."')";
	$emailInfo = $DB->fetch_one_array($sql);
	if(empty($emailInfo)){
		echo "<meta http-equiv=\"refresh\" content=\"0;URL=errorall.php?errid=rc_1012\">";
		exit;
	}
	//To Emails
	$toEmailArr = @explode(",",$emailInfo['e_toemail']);
	$toNameArr = @explode(",",$emailInfo['e_toname']);
	foreach($toEmailArr as $k => $email){
		if( $emailInfo['e_contactid'] >0 ||  $emailInfo['e_type'] == 3 ){
			$toEmails[] = $toNameArr[$k];
		}else{
			$toEmails[] = $toNameArr[$k]."[".$email."]";
		}
	}
	$emailInfo['e_toemail'] = @implode("<br>",$toEmails);
	$attachContent = attachContents($emailInfo['e_attachjobs']);
	$emailInfo['e_content'] = $emailInfo['e_content']." <br /><br />". $attachContent;
		
	//Attach Jobs
	$jobIds = @explode(",",$emailInfo['e_attachjobs']);
	if(!empty($jobIds)){
		$jobInfo = '';
		foreach($jobIds as $id){
			$sql = "SELECT jo_title, jo_copname, jo_copurl, jo_description, jo_address, jo_city, jo_state, jo_country FROM pa_job WHERE jo_uid='".$_SESSION['uid']."' AND jo_utype='recruiter' AND jo_id = '".$id."' ";
			$job = $DB->fetch_one_array($sql);
			if(!empty($job)){
				$jobInfo .= $job['jo_title'] ." ( ". $job['jo_address'] ." - ".$job['jo_city'].",".$state[$job['jo_state']].") <br />";
			}
		}
	}
	//Application job related
	if($emailInfo['e_joid']>0){
		$sql = "SELECT jo_title,jo_uid FROM pa_job WHERE jo_id = '".$emailInfo['e_joid']."'";
		$_jobrelated = $DB->fetch_one_array($sql);
		$smarty->assign("jobtitle",$_jobrelated['jo_title']);
		$smarty->assign("jobid",$emailInfo['e_joid']);
	}
	if($emailInfo['e_sentrcid'] != $_SESSION['uid']){
		//Update to is_read
		$sql = "UPDATE pa_email SET `e_isread` = 1 WHERE e_id = '".$eid."'";
		$DB->query($sql);
	}
	
	if($jobInfo == ''){$jobInfo = 'N/A';}
	$emailInfo['attachJobs'] = $jobInfo;
	$emailInfo['date'] = date("m-d-Y",$emailInfo['e_created']);
	$emailInfo['realname'] = $_SESSION['realname'];
	$emailInfo['e_fromname'] = ( $emailInfo['e_type'] == 3 )? $emailInfo['e_fromname'] : $emailInfo['e_fromname']." [".$emailInfo['e_fromemail']."] ";

	//check if they are friends already
	$emailInfo['areFriends'] = areFriends($emailInfo['e_receivedrcid'], $emailInfo['e_sentrcid'])?1:0;	
	//check if it's accepter
	$emailInfo['isAccepter'] = ($emailInfo['e_sentrcid'] == $_SESSION['uid'])?1:0;

	$sql = "SELECT re_isapproved FROM pa_contact WHERE re_id = '".$emailInfo[e_contactid]."'";
	$pa_contact = $DB->fetch_one_array($sql);
	$emailInfo[approved] = $pa_contact[re_isapproved];
	
	$smarty->assign("s",$emailInfo);

	if($emailInfo['e_receivedrcid'] == $_SESSION[uid]){
		$smarty->assign("inbox", 1);
	}
	if($emailInfo['e_contactid'] >0 && $_jobrelated['jo_uid'] == $_SESSION['uid']){
		$smarty->assign("replynewpage", 1);
	}

	$smarty->display('allleft.tpl');
	$smarty->display('viewemail.tpl');
	$smarty->display('footer.tpl');
	exit;
}

if($_GET[action] == 'updatestats' && $_GET[reid]) {
	$sql = "SELECT * FROM pa_email WHERE e_contactid = '".$_GET[reid]."' AND e_receivedrcid = '".$_SESSION[uid]."'";
	$pa_email = $DB->fetch_one_array($sql);

	if($pa_email[e_joid]) {
		$sql = "UPDATE pa_contact SET re_isapproved = '1' WHERE re_id = '".$pa_email[e_contactid]."'";
		$DB->query($sql);

		//Send Email
		require_once("./include/class.phpmailer.php");

		if(!empty($pa_email[e_fromemail])) {
				$mail=new PHPMailer();

				$mail->IsMail();
				$mail->From     = $_SESSION['useremail'];
				$mail->FromName = $_SESSION['realname'];
				$mail->AddAddress($pa_email[e_fromemail],$pa_email[e_fromname]);

				$mail->IsHTML(true);

				$jobDetail = getJobDetail($pa_email[e_joid]);
				$mail->Subject = "Approved: ".$jobDetail['jo_title'].", ER Job Req#".$pa_email[e_joid];
				$mail->Body = "<p>You are receiving this message because the sender has approved for you to work on this job.  You now can submit candidates to this job.  To get started, login to your account at <a href='enetrecruiter.com'>enetRecruiter.com</a>  then go to view the Approved to Submit jobs section. </p> 
				<p><span style='color:gray;'>NOTE: This message was sent to you by a member of enetRecruiter.com. For questions regarding this job, please contact the sender.  Any questions regarding your account please contact us at <a href='mailto:account@enetrecruiter.com'>account@enetrecruiter.com</a>. </span></p> ";

				$mail->CharSet = 'UTF-8';
				$mail->Send();
		}
	}
	echo "<meta http-equiv=\"refresh\" content=\"0;URL=sendemail.php?action=view&id=".$pa_email[e_id]."\">";
	exit;
}

if($_GET['action']=="send" || $_GET['action'] == "resend" ){

	if(trim($_POST['preview']) == "Preview"){//Preview
		$preview = 1;
		$smarty->assign("preview",1);
	}
	  
	  $err = '';
	  if($_GET['action'] == "send"){//send
		  if(trim($_POST['e_subject'])==''){
			  $err .= "Subject is required<br>";
		  }
		  if(trim($_POST['e_toemail'])=='' && $_POST['toall'] <> 1){
			  $err .= "Send-to email address is required<br>";
		  }
					
		  
	  }else{//resend
		 $id = $_GET['id']+0; 
		 if($id <= 1) {
			echo "<meta http-equiv=\"refresh\" content=\"0;URL=errorall.php?errid=rc_1012\">";
			exit;
		 }
		 $sql = "SELECT * FROM pa_email WHERE e_sentrcid = '".$_SESSION['uid']."' AND e_id = '".$id."' ";
		 $eInfo = $DB->fetch_one_array($sql);
	  }
	  $to_emails = array();
	  $to_names = array();
	  if($err == ''){
				
			   if($_GET['action'] == "send"){//send
					  if($_POST['toall'] == 1){ 
						  $is_toall = 1;
						  $sql = "SELECT myc_email,myc_firstname,myc_lastname from pa_mycontacts WHERE myc_rcid = '".$_SESSION['uid']."'";
						  $tp_contacts = $DB->fetch_all($sql);
							if(!empty($tp_contacts)){
								foreach($tp_contacts as $contact){
									$to_emails[] = $contact['myc_email'];
									$to_names[] = $contact['myc_firstname']." ".$contact['myc_lastname'];
								}
								$to_email = @implode(",",$to_emails);
								$to_name = @implode(",",$to_names);
							}
					  }else{
						  //to_email
						  $toArr = @explode(",",$_POST['e_toemail']);
						  $toArr = @array_unique($toArr);
						  foreach($toArr as $s){
								$_email = '';
								$_name = '';
								if(strpos($s,"||")){
									list($_email,$_name)=@explode("||",$s);
									$to_emails[] = $_email;
									$to_names[] = $_name;
								}else{
									//is_group
									if(is_numeric($s) && $s > 0){
										$sql = "SELECT * FROM pa_mycontacts WHERE FIND_IN_SET('".$s."',`myc_gid`) AND myc_rcid= '".$_SESSION['uid']."'";
										$gp_contacts = $DB->fetch_all($sql);
										if(!empty($gp_contacts)){
											foreach($gp_contacts as $contact){
												$to_emails[] = $contact['myc_email'];
												$to_names[] = $contact['myc_firstname']." ".$contact['myc_lastname'];
											}
										}
									}
								}
						  }
						  $to_emails = array_unique($to_emails);
						  $to_names = array_unique($to_names);
						
						  if(empty($to_emails)){
								echo "<meta http-equiv=\"refresh\" content=\"0;URL=errorall.php?errid=rc_1013\">";
								exit;
						  }

						  $to_email = @implode(",",$to_emails);
						  $to_name = @implode(",",$to_names);
					  }

					   //attach jobs
					  $attach = @explode(",",$_POST['attachJobs']);
					  $attach = @array_unique($attach);
					  $attach = @implode(",",$attach);
			   }else{//resend
					$to_emails = @explode(",",$eInfo['e_toemail']);
					$to_names = @explode(",",$eInfo['e_toname']);
					$attach = $eInfo['e_attachjobs'];
					$_POST['e_subject'] = $eInfo['e_subject'];
					$_POST['content'] = $eInfo['e_content'];
			   }
			  
			  $attachContent = attachContents($attach);
			  $content = $_POST['content'] ." <br /><br />". $attachContent;
				
			   //write to file
			   $file = "/tmp/attach".time().".doc";

			  $handle = @fopen($file, 'w');
			  @fwrite($handle,$attachContent);
			  @fclose($handle);
	  }

		
	  if($err == ''){
			if($preview == 1){//Preview
				$emailInfo['e_subject'] = $_POST['e_subject'];
				$emailInfo['e_fromemail'] = $_SESSION['useremail'];
			
				$attachContent = attachContents($_POST['attachJobs']);
				$emailInfo['e_content'] = $_POST['content'] ." <br /><br />". $attachContent;
				//To Emails
				$toEmailArr = @explode(",",$to_email);
				$toNameArr = @explode(",",$to_name);
				foreach($toEmailArr as $k => $email){
					$toEmails[] = $toNameArr[$k]." [".$email."]";
				}
				$emailInfo['e_toemail'] = @implode("<br>",$toEmails);
					
				//Attach Jobs
				$jobIds = @explode(",",$_POST['attachJobs']);
				if(is_array($jobIds) && count($jobIds)>0){
					$jobInfo = '';
					foreach($jobIds as $id){
						$sql = "SELECT jo_title, jo_copname, jo_copurl, jo_description, jo_address, jo_city, jo_state, jo_country FROM pa_job WHERE jo_uid='".$_SESSION['uid']."' AND jo_utype='recruiter' AND jo_id = '".$id."'";
						$job = $DB->fetch_one_array($sql);
						if(!empty($job)){
							$jobInfo .= $job['jo_title'] ." ( ".$id.") <br />";
						}
					}
				}
				if($jobInfo == ''){$jobInfo = 'N/A';}
				$emailInfo['attachJobs'] = $jobInfo;
				$emailInfo['date'] = date("m-d-Y");
				$emailInfo['realname'] = $_SESSION['realname'];
				$smarty->assign("s",$emailInfo);


				$smarty->display('allleft.tpl');
				$smarty->display('previewemail.tpl');
				$smarty->display('footer.tpl');
				exit;
			}

			
		    if($_GET['action'] == "send"){//send
				//Save Email
				$sql = " INSERT INTO pa_email (
					`e_istoall`,
					`e_sentrcid`,
					`e_fromemail`,
					`e_fromname`,
					`e_toemail`,
					`e_toname`,
					`e_subject`,
					`e_content`,
					`e_attachjobs`,
					`e_created`							
				) VALUES (
					 '".$is_toall."',
					 '".$_SESSION['uid']."',
					 '".$_SESSION['useremail']."',
					 '".$_SESSION['realname']."',
					 '".$to_email."',
					 '".$to_name."',
					 '".mysql_real_escape_string($_POST['e_subject'])."',
					 '".mysql_real_escape_string($_POST['content'])."',
					 '".mysql_real_escape_string($_POST['attachJobs'])."',
					'".time()."'
				)";

				
				$DB->query($sql);
			}

			

			//Send Email
			require_once("./include/class.phpmailer.php");
			
			foreach($to_emails as $key=>$single_email){
				$mail=new PHPMailer();

				$mail->IsMail();
				$mail->From     = $_SESSION['useremail'];
				$mail->FromName = $_SESSION['realname'];
				//foreach($to_emails as $key => $single_email){
				$mail->AddAddress($single_email,$to_names[$key]);
				//}
				if(@filesize($file)>0){
					$mail->AddAttachment($file);
				}
				
				if(!empty($_FILES)){
					$mail->AddAttachment($_FILES['attachfile']['tmp_name'],$_FILES['attachfile']['name']);
				}

				$mail->IsHTML(true);
				$mail->Subject = stripslashes($_POST['e_subject']);
				$mail->Body = stripslashes($content);

				$mail->CharSet = 'UTF-8';

				$mail->Send();
			}

			$err  = "<h3 style=\"color:red\">Sent Successfully!</h3><meta http-equiv=\"refresh\" content=\"2;URL=myemails.php\">";
	  }else{
			$smarty->assign("e_subject",$_POST['e_subject']);
			$smarty->assign("toall",$_POST['toall']);
	  }
}

//all my contacts
$sql = "SELECT myc_email,myc_firstname,myc_lastname from pa_mycontacts WHERE myc_rcid = '".$_SESSION['uid']."' ORDER BY myc_firstname ASC ";
$tp_contacts = $DB->fetch_all($sql);
if(!empty($tp_contacts)){
	foreach($tp_contacts as $contact){
		$contacts[] = '{"name":"'.$contact['myc_firstname'].' '.$contact['myc_lastname'].' ('.$contact['myc_email'].')","id":"'.$contact['myc_email'].'||'.$contact['myc_firstname'].' '.$contact['myc_lastname'].'"}';
		//$contactArr[$contact['myc_email']] = $contact['myc_firstname'].' '.$contact['myc_lastname'];
	}
}


//all my groups
$sql = "SELECT * FROM pa_contactgroup WHERE cgp_rcid = '".$_SESSION['uid']."' ORDER BY cgp_title ASC";
$tp_groups = $DB->fetch_all($sql);
if(!empty($tp_groups) && $_SESSION['status'] == 'Premium'){
	foreach($tp_groups as $group){
		$contacts[] = '{"name":"Group: '.$group['cgp_title'].'","id":"'.$group['cgp_id'].'"}';
		$groupArr[$group['cgp_id']] = $group['cgp_title'];
	}
}

//all my jobs
$sql = "SELECT jo_id,jo_title,jo_city,jo_state FROM pa_job WHERE jo_uid = '".$_SESSION['uid']."' AND jo_utype='recruiter' AND jo_status <> '3' ORDER BY jo_id DESC";
$tp_jobs = $DB->fetch_all($sql);
if(!empty($tp_jobs)){
	foreach($tp_jobs as $job){
		$jobs[] = '{"name":"=>'.$job['jo_title'].' ('.$job['jo_id'].')","id":"'.$job['jo_id'].'"}';
		$jobArr[$job['jo_id']] = $job['jo_title'];
	}
}
$jobOptions = @implode(",",$jobs);
$jobOptions = str_replace("++","+",$jobOptions);
//posted contact
$toArr = @explode(",",$_POST['e_toemail']);
$toArr = @array_unique($toArr);
foreach($toArr as $s){
	$_email = '';
	$_name = '';
	if(strpos($s,"||")){
		list($_email,$_name)=@explode("||",$s);
		$postcontacts[] = '{"name":"'.$_email.' ('.$_name.')","id":"'.$_email.'||'.$_name.'"}';
	}else{
		if($_SESSION['status'] == 'Premium'){
			//is_group
			if(is_numeric($s) && $s > 0){
				$postcontacts[] = '{"name":"Group: '.$groupArr[$s].'","id":"'.$s.'"}';
			}
		}
	}
}
$postcontactsOptions = @implode(",",$postcontacts);
$postcontactsOptions = str_replace("++","+",$postcontactsOptions);
$smarty->assign("postcontacts","prePopulate:[".$postcontactsOptions."],");


//posted jobs
$contactOptions = @implode(",",$contacts);
if($_POST['attachJobs']){
	$postjobids = @explode(",",$_POST['attachJobs']);
	foreach($postjobids as $id){
		$postjobs[] = '{"name":"=>'.$jobArr[$id].' ('.$id.')","id":"'.$id.'"}';
	}
	$postjobOptions = @implode(",",$postjobs);
	$postjobOptions = str_replace("++","+",$postjobOptions);
	$smarty->assign("postjobs","prePopulate:[".$postjobOptions."],");
}


//FCKeditor
$oFCKeditor = new FCKeditor("content") ;
$oFCKeditor->BasePath	= "FCKeditor/" ;
$oFCKeditor->Value = '' ;
$oFCKeditor->Width = 500;
$oFCKeditor->Height =300;
$oFCKeditor->ToolbarSet = "Basic";
//$oFCKeditor->Value = "<p><b>Dear  :</b><p><br /><br /><br /><br /><br /><br /><br /><br /><p><b>Best Regards<b></p><p><b>".$_SESSION['realname']."<b></p><p><b>".$_SESSION['phone']."<b></p>";
$oFCKeditor->Value = ($_POST['content'] != '')?$_POST['content']:"";

$smarty->assign("fckcontent",$oFCKeditor->CreateHtml());


if($err!=''){
$smarty->assign("err",$err);
}
$smarty->assign("mycontacts",$contactOptions);
$smarty->assign("myjobs",$jobOptions);
$smarty->assign("search",$reg_data);
$smarty->display('allleft.tpl');
$smarty->display('sendemail.tpl');
$smarty->display('footer.tpl');


function attachContents($jobIds){
	global $state,$country,$DB,$_SESSION;
	$ids = @explode(",",$jobIds);
	if($ids[0] != ''){
		$str .= "<table width='520'>
					<tr><td colspan='2'><b>Job Details<br></td></tr>";
		$str .= "	<tr><td colspan='2'><br>-----------------------------<br></td></tr>";
		foreach($ids as $id){
			$sql = "SELECT jo_title, jo_copname, jo_copurl, jo_description, jo_address, jo_city, jo_state, jo_country FROM pa_job WHERE jo_uid='".$_SESSION['uid']."' AND jo_utype='recruiter' AND jo_id = '".$id."'";
			$job = $DB->fetch_one_array($sql);
			$str .= "<tr><td width='25%' valign='top'><b>Req#:</b></td><td valign='top'>".$id."</td></tr>";
			$str .= "<tr><td width='25%' valign='top'><b>Title:</b></td><td valign='top'>".$job['jo_title']."</td></tr>";
			$str .= "<tr><td valign='top'><b>Location:</b></td><td valign='top'>".$job['jo_address']."<br />".$job['jo_city'].",".$state[$job['jo_state']].",".$country[$job['jo_country']]."</td></tr>";
			if(preg_match("/Please select or click on a PASTE option above/i",$job['jo_description'])){
				$job['jo_description'] = "No Descriptions";
			}
			$str .= "<tr><td valign='top'><b>Description:</b></td><td valign='top'>".$job['jo_description']."</td></tr>";

			$str .= "	<tr><td colspan='2'><br>-----------------------------<br></td></tr>";
		}
		$str .= "</table>";
	}
	return $str;
}


?>